import React, { useState, useEffect } from 'react'
import { 
  Row, 
  Col, 
  Card, 
  Table, 
  Button, 
  Tag, 
  Space, 
  Select, 
  Modal,
  Form,
  message,
  Progress,
  Switch,
  Input,
  DatePicker
} from 'antd'
import { 
  SendOutlined, 
  PlayCircleOutlined, 
  PauseCircleOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons'
import { mockApi, PublishChannel, ContentItem } from '@/services/mockData'
import dayjs from 'dayjs'

const { Option } = Select

interface PublishTask {
  id: string
  title: string
  contentId: string
  channels: string[]
  scheduleTime: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress: number
  createTime: string
}

const PublishManagement: React.FC = () => {
  const [channels, setChannels] = useState<PublishChannel[]>([])
  const [contentList, setContentList] = useState<ContentItem[]>([])
  const [publishTasks, setPublishTasks] = useState<PublishTask[]>([])
  const [loading, setLoading] = useState(true)
  const [modalVisible, setModalVisible] = useState(false)
  const [detailModalVisible, setDetailModalVisible] = useState(false)
  const [currentTask, setCurrentTask] = useState<PublishTask | null>(null)
  const [form] = Form.useForm()

  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = async () => {
    setLoading(true)
    try {
      const [channelsData, contentData] = await Promise.all([
        mockApi.getPublishChannels(),
        mockApi.getContentList()
      ])
      setChannels(channelsData)
      setContentList(contentData)
      
      // 从localStorage获取发布任务数据，如果没有则使用模拟数据
      const storedTasks = localStorage.getItem('publishTasks')
      if (storedTasks) {
        setPublishTasks(JSON.parse(storedTasks))
      } else {
        // 模拟发布任务数据
        const tasks: PublishTask[] = [
          {
            id: '1',
            title: '春季农业技术推广',
            contentId: '1',
            channels: ['1', '2'],
            scheduleTime: '2024-03-16 09:00',
            status: 'completed',
            progress: 100,
            createTime: '2024-03-15 14:30'
          },
          {
            id: '2',
            title: '乡村旅游宣传',
            contentId: '3',
            channels: ['1'],
            scheduleTime: '2024-03-16 14:00',
            status: 'processing',
            progress: 60,
            createTime: '2024-03-15 16:20'
          },
          {
            id: '3',
            title: '农产品电商直播',
            contentId: '2',
            channels: ['3'],
            scheduleTime: '2024-03-17 10:00',
            status: 'pending',
            progress: 0,
            createTime: '2024-03-15 18:45'
          }
        ]
        setPublishTasks(tasks)
      }
    } catch (error) {
      message.error('获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  const handleCreateTask = () => {
    form.resetFields()
    setModalVisible(true)
  }

  const handleSubmit = async (values: any) => {
    try {
      // 模拟创建发布任务
      const newTask: PublishTask = {
        id: Date.now().toString(),
        title: values.title,
        contentId: values.contentId,
        channels: values.channels,
        scheduleTime: values.scheduleTime.format('YYYY-MM-DD HH:mm'),
        status: 'pending',
        progress: 0,
        createTime: dayjs().format('YYYY-MM-DD HH:mm')
      }
      
      const updatedTasks = [newTask, ...publishTasks]
      setPublishTasks(updatedTasks)
      // 保存到localStorage实现数据持久化
      localStorage.setItem('publishTasks', JSON.stringify(updatedTasks))
      setModalVisible(false)
      message.success('发布任务创建成功')
    } catch (error) {
      message.error('创建失败')
    }
  }

  const handleStatusChange = (taskId: string, status: PublishTask['status']) => {
    const updatedTasks = publishTasks.map(task => 
      task.id === taskId ? { ...task, status } : task
    )
    setPublishTasks(updatedTasks)
    // 保存到localStorage
    localStorage.setItem('publishTasks', JSON.stringify(updatedTasks))
    message.success('状态更新成功')
  }

  // 添加渠道状态改变处理函数
  const handleChannelStatusChange = (channelId: string, checked: boolean) => {
    setChannels(channels.map(channel => 
      channel.id === channelId 
        ? { ...channel, status: checked ? 'active' : 'inactive' } 
        : channel
    ))
    message.success(`渠道${checked ? '已启用' : '已禁用'}`)
  }

  // 添加查看详情处理函数
  const handleViewDetail = (task: PublishTask) => {
    setCurrentTask(task)
    setDetailModalVisible(true)
  }

  // 添加删除任务处理函数
  const handleDeleteTask = (taskId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个发布任务吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const updatedTasks = publishTasks.filter(task => task.id !== taskId)
        setPublishTasks(updatedTasks)
        // 保存到localStorage
        localStorage.setItem('publishTasks', JSON.stringify(updatedTasks))
        message.success('删除成功')
      }
    })
  }

  const getStatusConfig = (status: PublishTask['status']) => {
    const configs = {
      pending: { color: 'default', text: '等待中', icon: <PauseCircleOutlined /> },
      processing: { color: 'processing', text: '发布中', icon: <PlayCircleOutlined /> },
      completed: { color: 'success', text: '已完成', icon: <SendOutlined /> },
      failed: { color: 'error', text: '失败', icon: <DeleteOutlined /> }
    }
    return configs[status]
  }

  const getChannelName = (channelId: string) => {
    const channel = channels.find(c => c.id === channelId)
    return channel?.name || '未知渠道'
  }

  const getContentTitle = (contentId: string) => {
    const content = contentList.find(c => c.id === contentId)
    return content?.title || '未知内容'
  }

  const columns = [
    {
      title: '任务名称',
      dataIndex: 'title',
      key: 'title',
      render: (text: string) => <span style={{ fontWeight: 500 }}>{text}</span>
    },
    {
      title: '发布内容',
      key: 'content',
      render: (record: PublishTask) => getContentTitle(record.contentId)
    },
    {
      title: '发布渠道',
      key: 'channels',
      render: (record: PublishTask) => (
        <Space wrap>
          {record.channels.map(channelId => (
            <Tag key={channelId} color="blue">
              {getChannelName(channelId)}
            </Tag>
          ))}
        </Space>
      )
    },
    {
      title: '发布时间',
      dataIndex: 'scheduleTime',
      key: 'scheduleTime',
      render: (time: string) => dayjs(time).format('MM-DD HH:mm')
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: PublishTask['status']) => {
        const config = getStatusConfig(status)
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        )
      }
    },
    {
      title: '进度',
      key: 'progress',
      render: (record: PublishTask) => (
        <Progress 
          percent={record.progress} 
          size="small" 
          status={record.status === 'failed' ? 'exception' : 'normal'}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (record: PublishTask) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          {record.status === 'pending' && (
            <Button 
              type="link" 
              icon={<PlayCircleOutlined />} 
              size="small"
              onClick={() => handleStatusChange(record.id, 'processing')}
            >
              开始
            </Button>
          )}
          {record.status === 'processing' && (
            <Button 
              type="link" 
              icon={<PauseCircleOutlined />} 
              size="small"
              onClick={() => handleStatusChange(record.id, 'pending')}
            >
              暂停
            </Button>
          )}
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDeleteTask(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  return (
    <div>
      <div className="page-title">
        <SendOutlined />
        发布管理
      </div>

      <Row gutter={[16, 16]}>
        {/* 发布渠道概览 */}
        <Col xs={24} lg={8}>
          <Card title="发布渠道" className="custom-card">
            <Space direction="vertical" style={{ width: '100%' }}>
              {channels.map(channel => (
                <Card key={channel.id} size="small">
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <div style={{ fontWeight: 500 }}>{channel.name}</div>
                      <div style={{ color: '#999', fontSize: 12 }}>
                        粉丝: {channel.followers.toLocaleString()} | 今日浏览: {channel.todayViews}
                      </div>
                    </div>
                    <Switch 
                      checked={channel.status === 'active'} 
                      size="small" 
                      onChange={(checked) => handleChannelStatusChange(channel.id, checked)}
                    />
                  </div>
                </Card>
              ))}
            </Space>
          </Card>
        </Col>

        {/* 发布任务列表 */}
        <Col xs={24} lg={16}>
          <Card 
            title="发布任务"
            extra={
              <Button type="primary" icon={<SendOutlined />} onClick={handleCreateTask}>
                新建任务
              </Button>
            }
            className="custom-card"
          >
            <Table
              columns={columns}
              dataSource={publishTasks}
              loading={loading}
              rowKey="id"
              pagination={{
                total: publishTasks.length,
                pageSize: 10,
                showSizeChanger: true
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* 新建发布任务模态框 */}
      <Modal
        title="新建发布任务"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="title"
            label="任务名称"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input placeholder="请输入任务名称" />
          </Form.Item>

          <Form.Item
            name="contentId"
            label="发布内容"
            rules={[{ required: true, message: '请选择发布内容' }]}
          >
            <Select placeholder="请选择发布内容">
              {contentList.map(content => (
                <Option key={content.id} value={content.id}>
                  {content.title}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="channels"
            label="发布渠道"
            rules={[{ required: true, message: '请选择发布渠道' }]}
          >
            <Select mode="multiple" placeholder="请选择发布渠道">
              {channels.map(channel => (
                <Option key={channel.id} value={channel.id}>
                  {channel.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="scheduleTime"
            label="发布时间"
            rules={[{ required: true, message: '请选择发布时间' }]}
          >
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm"
              style={{ width: '100%' }}
              placeholder="请选择发布时间"
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                创建任务
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 任务详情模态框 */}
      <Modal
        title="任务详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
        centered
      >
        {currentTask && (
          <div>
            <div style={{ marginBottom: '16px' }}>
              <h3 style={{ margin: '0 0 8px 0' }}>{currentTask.title}</h3>
              <div style={{ display: 'flex', gap: '16px', marginBottom: '12px' }}>
                <Tag color={getStatusConfig(currentTask.status).color}>
                  {getStatusConfig(currentTask.status).text}
                </Tag>
                <span style={{ color: '#666' }}>创建时间: {currentTask.createTime}</span>
              </div>
            </div>
            
            <div style={{ marginBottom: '16px' }}>
              <h4 style={{ margin: '0 0 8px 0', fontSize: '14px' }}>基本信息</h4>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <p style={{ margin: '0 0 4px 0', fontSize: '12px', color: '#999' }}>发布内容</p>
                  <p style={{ margin: 0 }}>{getContentTitle(currentTask.contentId)}</p>
                </div>
                <div>
                  <p style={{ margin: '0 0 4px 0', fontSize: '12px', color: '#999' }}>发布时间</p>
                  <p style={{ margin: 0 }}>{currentTask.scheduleTime}</p>
                </div>
              </div>
            </div>
            
            <div style={{ marginBottom: '16px' }}>
              <h4 style={{ margin: '0 0 8px 0', fontSize: '14px' }}>发布渠道</h4>
              <Space wrap>
                {currentTask.channels.map(channelId => (
                  <Tag key={channelId} color="blue">
                    {getChannelName(channelId)}
                  </Tag>
                ))}
              </Space>
            </div>
            
            <div>
              <h4 style={{ margin: '0 0 8px 0', fontSize: '14px' }}>发布进度</h4>
              <Progress 
                percent={currentTask.progress} 
                status={currentTask.status === 'failed' ? 'exception' : 'normal'}
                style={{ marginBottom: '8px' }}
              />
              <p style={{ margin: 0, fontSize: '12px', color: '#666' }}>
                {currentTask.progress}% 已完成
              </p>
            </div>
          </div>
        )}
      </Modal>
    </div>
  )
}

export default PublishManagement